<?php

namespace common\models;

use Yii;
use yii\base\Model;

class CM_Model extends Model
{

    private static $db;

    private function db()
    {
        yii::$app->debug->stime("conn");
        self::$db = $connection = Yii::$app->db2;
        yii::$app->debug->etime("conn");
    }

    /**
     * 查询一条数据
     * @param $sql
     * @return mixed
     */
    protected function row($sql)
    {
        self::db();
        $row = self::$db->createCommand($sql)
            ->queryOne();
        return $row;
    }

    /**
     * 查询多条数据
     * @param $sql
     * @return mixed
     */
    protected function rows($sql)
    {
        self::db();
        $row = self::$db->createCommand($sql)
            ->queryAll();
        return $row;
    }

    /**
     * 新增
     * @param $table
     * @param $data
     * @return mixed
     */
    protected function insert($table, $data)
    {
        self::db();
        self::$db->createCommand()->insert($table, $data)->execute();
        return self::$db->getLastInsertId();
    }

    /**
     * 修改
     * @param $table
     * @param $data
     * @param $where
     */
    protected function update($table, $data, $where)
    {
        self::db();
        self::$db->createCommand()->update($table, $data, $where)->execute();
    }

    /**
     * 调用存储过程
     */
    protected function call()
    {
        self::db();
        self::$db->createCommand('call P_INSERT_A(:in_a,@num);')->bindValues([":in_a" => '嘎嘎'])->execute();
        $s = self::$db->createCommand("select @num as id");
        $result = $s->queryOne();
        echo json_encode($result);
        exit;
        $reg = "davafy@davafy.com";
        $cmd = self::$db->createCommand("call P_INSERT_A(:name,@num)");
        $cmd->bindValues([":in_a" => '嘎嘎']);
        $res = $cmd->queryOne();
        $s = self::$db->createCommand("select @num as id");
        $row = $s->queryOne();

        echo json_encode($row);
        exit;
        //$row = self::$db->createCommand("call P_INSERT_A('你ssss好',@num);")->queryAll();

    }

    /***********************************************************************************************/
    /*************************************************************************** 统一返回调用结果 **/
    private function result($status, $msg, $data)
    {
        return array("status" => $status, "msg" => $msg, "data" => $data);
    }

    protected function error($msg = '', $data = array())
    {
        return self::result(false, $msg, $data);
    }

    protected function success($data = array(), $msg = '')
    {
        return self::result(true, $msg, $data);
    }

}
